package com.terrynoya.fight.system.camera
{
	import com.terrynoya.geom.MVector2D;
	
	import flash.geom.Rectangle;

	public class MCameraController
	{
		private var _stageWidth:int;
		private var _stageHeight:int;
		
		private var _camera:MCamera;
		
		private var _items:Array;
		
		public function MCameraController(stageWidth:int,stageHeight:int,viewPortWidth:int,viewPortHeight:int)
		{
			this._stageWidth = stageWidth;
			this._stageHeight = stageHeight;
			this._items = new Array();
			this._camera = new MCamera(new Rectangle(0,0,viewPortWidth,viewPortHeight));
			this.moveCameraTo(new MVector2D());
		}
		
		public function get items():Array
		{
			return _items;
		}

		public function clear():void
		{
			this._items = [];
		}
		
		public function get camera():MCamera
		{
			return _camera;
		}

		public function addItem(value:ICameraItem):void
		{
			this._items.push(value);
		}
		
		public function update():void
		{
			for (var i:int = 0; i < this._items.length; i++) 
			{
				var item:ICameraItem = this._items[i];
				this.transToCamera(item);
			}
		}
		
		private function transToCamera(item:ICameraItem):void
		{
			var cameraPos:MVector2D = this.globalToCamera(item.position);
			item.cameraPos = cameraPos;
//			item.view.x = cameraPos.x; 
//			item.view.y = cameraPos.y;
		}
		
		public function moveCameraTo(value:MVector2D):void
		{
			var cx:Number = Math.max(this._camera.width/2,Math.min(value.x,this._stageWidth - this._camera.width/2));
			var cy:Number = Math.max(this._camera.height/2,Math.min(value.y,this._stageHeight - this._camera.height/2));
			this._camera.position = new MVector2D(cx,cy);
		}
		
		public function globalToCamera(pos:MVector2D):MVector2D
		{
			var cameraPos:MVector2D = pos.substract(this._camera.position).add(new MVector2D(this._camera.width/2,this._camera.height/2));
			return cameraPos;
		}
	}
}